package com.duolai.bean;

import com.spring.annotation.Component;
import com.spring.interfaces.BeanPostProcessor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @program: duolai-spring-01
 * @description: 自定义后置处理器
 * @author: chaidl  ！
 * @create: 2021-09-05 16:11
 */
@Component
public class DuoLaiBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        if (beanName.equals("userService")){
            Object proxyInstance = Proxy.newProxyInstance(DuoLaiBeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    //切面
                    System.out.println("初始化后");
                    //执行完切面方法以后执行原本的方法
                    return method.invoke(bean, args);
                }
            });
            return proxyInstance;
        }
        return bean;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {

        return bean;
    }
}
